package com.example.pan.data

import com.android.volley.Request
import com.android.volley.RequestQueue
import com.example.pan.http.GsonRequest
import com.example.pan.model.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.suspendCancellableCoroutine
import javax.inject.Inject
import kotlin.coroutines.resumeWithException

class DriveDataSourceImpl @Inject constructor(
    private val queue: RequestQueue
) : IDriveDataSource {

    @ExperimentalCoroutinesApi
    fun getUserInfo(token: String) = flow<UserInfo> {
        emit(suspendCancellableCoroutine { continuation ->
            val url = "https://pan.baidu.com/rest/2.0/xpan/nas?method=uinfo&access_token=${token}"
            val headers = mutableMapOf<String, String>()
            headers["User-Agent"] = "pan.baidu.com"
            GsonRequest(url, Request.Method.GET, UserInfo::class.java, headers, listener = {
                continuation.resume(it) { e ->
                    continuation.resumeWithException(e)
                }
            }, errorListener = {
                continuation.resumeWithException(it)
            }).also { queue.add(it) }
        })
    }.flowOn(Dispatchers.IO)

}